package com.starleague.battletech.game.jpa.appengine;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import com.starleague.battletech.BattletechException;
import com.starleague.battletech.game.IBattletechGame;
import com.starleague.battletech.game.IBattletechTeamFactory;

public class BattletechTeamGaeFactory
        implements IBattletechTeamFactory
{
    // TODO: Cleanse our inputs before ever hitting these model objects!
    @Override
    public BattletechTeamGae createTeam(IBattletechGame game,
                                        String name) throws BattletechException
    {
        Preconditions.checkNotNull(game);

        // TODO: Use some other method for this. isBlank or trimToBlank(esp!)
        String trimmedName = Strings.emptyToNull(name.trim()); // Yay exceptions!
        // TODO: Use a comparator and Collection.search method or something
        for (BattletechTeamGae team : ((BattletechGameGae) game).getTeams())
        {
            if (team.getName().equalsIgnoreCase(trimmedName))
                throw new BattletechException("Cannot add Team with duplicate name [" + name + "]: " + team);
        }

        BattletechTeamGae team = new BattletechTeamGae(((BattletechGameGae) game), name);
        ((BattletechGameGae) game).getTeams().add(team);
        return team;
    }
}
